﻿using System.Net.WebSockets;
using System.Text;

namespace HuaWeiSIsClient;

public class RasrDemo
{
        private readonly Uri _serverUri; // WebSocket服务地址
    private readonly string _token; // token认证信息

    public RasrDemo(string endpoint, string projectId, string token)
    {
        _serverUri = new Uri($"wss://{endpoint}/v1/{projectId}/rasr/continue-stream");
        _token = token;
    }

    public async Task RunDemoAsync()
    {
        using (var webSocket = new ClientWebSocket())
        {
            webSocket.Options.SetRequestHeader("X-Auth-Token", _token);
            try
            {
                await webSocket.ConnectAsync(_serverUri, CancellationToken.None);

                Console.WriteLine("Connected");

                var startMessage = "{\"command\": \"START\", \"config\": {\"audio_format\": \"pcm8k16bit\", \"property\": \"chinese_8k_common\"}}";
                await SendStringAsync(webSocket, startMessage);

                byte[] audioData = null; // 存放音频数据的byte数组，需要替换为实际音频数据
                await webSocket.SendAsync(new ArraySegment<byte>(audioData), WebSocketMessageType.Binary, true, CancellationToken.None);

                var endMessage = "{\"command\": \"END\", \"cancel\": false}";
                await SendStringAsync(webSocket, endMessage);

                await Task.Delay(10000); // 等待一段时间以接收服务器的响应消息

                await webSocket.CloseAsync(WebSocketCloseStatus.NormalClosure, string.Empty, CancellationToken.None);
            }
            catch (Exception e)
            {
                Console.WriteLine($"Exception: {e}");
            }
        }
    }

    private static async Task SendStringAsync(ClientWebSocket webSocket, string data)
    {
        var buffer = Encoding.UTF8.GetBytes(data);
        await webSocket.SendAsync(new ArraySegment<byte>(buffer), WebSocketMessageType.Text, true, CancellationToken.None);
    }

    public static void Main(string[] args)
    {
        var endpoint = "your_endpoint_here"; // 需要替换成实际的endpoint
        var projectId = "your_project_id_here"; // 需要替换成实际的project_id
        var token = "your_token_here"; // 需要替换成实际的token

        var demo = new RasrDemo(endpoint, projectId, token);
        demo.RunDemoAsync().GetAwaiter().GetResult();
    }
}